package com.hemaapp.yjnh.fragment;

import java.util.ArrayList;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import xtom.frame.util.XtomToastUtil;
import xtom.frame.view.XtomRefreshLoadmoreLayout;
import xtom.frame.view.XtomRefreshLoadmoreLayout.OnStartListener;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.hemaapp.hm_FrameWork.HemaNetTask;
import com.hemaapp.hm_FrameWork.result.HemaBaseResult;
import com.hemaapp.hm_FrameWork.result.HemaPageArrayResult;
import com.hemaapp.hm_FrameWork.view.RefreshLoadmoreLayout;
import com.hemaapp.yjnh.BaseApplication;
import com.hemaapp.yjnh.BaseHttpInformation;
import com.hemaapp.yjnh.R;
import com.hemaapp.yjnh.ViewPagerFragment;
import com.hemaapp.yjnh.activity.FarmerCustomOrderDetailActivity;
import com.hemaapp.yjnh.adapter.FarmerCustomOrderAdapter;
import com.hemaapp.yjnh.adapter.RecyclerTenDecoration;
import com.hemaapp.yjnh.bean.EventBusConfig;
import com.hemaapp.yjnh.bean.EventBusMsg;
import com.hemaapp.yjnh.bean.FarmerCustomOrder;
import com.hemaapp.yjnh.bean.User;
import com.hemaapp.yjnh.listener.OrderItemClickListener;
import com.hemaapp.yjnh.view.DeliveryDialog;

/**田家的定制订单列表
 * @author GuiyouZhang
 * 创建时间：2015年9月23日 上午11:11:35
 * 最后修改时间：上午11:11:35
 */
public class FarmerCustomizeOrderListFragment extends ViewPagerFragment implements OrderItemClickListener {

	private RefreshLoadmoreLayout parentLayout;
	private RecyclerView recyclerView;

	private User user;
	private ArrayList<FarmerCustomOrder> mDatas = new ArrayList<>();
	private FarmerCustomOrderAdapter adapter;
    String keytype = "1";
	private int page = 0;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.fragment_viewpager_refresh_recycler);
		user = BaseApplication.getInstance().getUser();
		super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        if (savedInstanceState != null) {
            keytype = savedInstanceState.getString("keytype");
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putString("keytype", keytype);
        super.onSaveInstanceState(outState);
    }
    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

	public void setKeytype(String keytype) {
		this.keytype = keytype;
	}

	@Override
	protected void findView() {
		parentLayout = (RefreshLoadmoreLayout) findViewById(R.id.refreshLoadmoreLayout);
		recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
	}

	@Override
	protected void setListener() {
		parentLayout.setOnStartListener(new OnStartListener() {
			@Override
			public void onStartRefresh(XtomRefreshLoadmoreLayout v) {
				page=0;
				getCustomizeList();
			}

			@Override
			public void onStartLoadmore(XtomRefreshLoadmoreLayout v) {
				page++;
				getCustomizeList();
			}
		});
		LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
		layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
		recyclerView.setLayoutManager(layoutManager);
	}

    /**获取田家的农作物定制订单
	 * 
	 */
	private void getCustomizeList() {
		getNetWorker().getFarmerCustomOrderList(user.getToken(), keytype, page+"");
	}
	
	@Override
	protected void callBeforeDataBack(HemaNetTask netTask) {
		BaseHttpInformation information = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (information) {
		case FARMER_CUSTOM_ORDER_LIST:
		case ORDER_SAVEOPERATE:
			showProgressDialog("请稍候");
			break;
		default:
			break;
		}
	}

	@Override
	protected void callAfterDataBack(HemaNetTask netTask) {
		BaseHttpInformation information = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (information) {
		case FARMER_CUSTOM_ORDER_LIST:
		case ORDER_SAVEOPERATE:
			cancelProgressDialog();
			break;
		}
	}

	@Override
	protected void callBackForServerSuccess(HemaNetTask netTask,
			HemaBaseResult baseResult) {
		BaseHttpInformation information = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (information) {
		case FARMER_CUSTOM_ORDER_LIST:
			String page = netTask.getParams().get("page");
			HemaPageArrayResult<FarmerCustomOrder> aResult = (HemaPageArrayResult<FarmerCustomOrder>) baseResult;
			if (aResult == null || aResult.getObjects() == null) {
				return;
			}
			if ("0".equals(page)) {// 刷新
				parentLayout.refreshSuccess();
				mDatas.clear();
                mDatas.addAll(aResult.getObjects());
				if (aResult.getObjects().size() == 0)
					parentLayout.setLoadmoreable(false);
				else
					parentLayout.setLoadmoreable(true);
			} else {// 更多
				parentLayout.loadmoreSuccess();
				if (aResult.getObjects().size() > 0) {
                    mDatas.addAll(aResult.getObjects());
				} else {
					parentLayout.setLoadmoreable(false);
					XtomToastUtil.showShortToast(getActivity(), "已经到最后啦");
				}
			}
			refreshData();
			break;
		case ORDER_SAVEOPERATE:
			XtomToastUtil.showShortToast(getActivity(), "操作成功");
			EventBusMsg msg = new EventBusMsg();
			msg.setType(EventBusConfig.UPDATE_ORDER);
			EventBus.getDefault().post(msg);
			break;
		}
	}

	@Override
	protected void callBackForServerFailed(HemaNetTask netTask,
			HemaBaseResult baseResult) {
		BaseHttpInformation information = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (information) {
		case FARMER_CUSTOM_ORDER_LIST:
			String page = netTask.getParams().get("page");
			if ("0".equals(page)) {// 刷新
				parentLayout.refreshFailed();
			} else {// 更多
				parentLayout.loadmoreFailed();
			}
			XtomToastUtil.showShortToast(getActivity(), "获取订单失败,"+baseResult.getMsg());
			break;
		case ORDER_SAVEOPERATE:
			XtomToastUtil.showShortToast(getActivity(), "操作失败,"+baseResult.getMsg());
			break;
		default:
			break;
		}
	}

	@Override
	protected void callBackForGetDataFailed(HemaNetTask netTask, int failedType) {
		BaseHttpInformation information = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (information) {
		case FARMER_CUSTOM_ORDER_LIST:
			String page = netTask.getParams().get("page");
			if ("0".equals(page)) {// 刷新
				parentLayout.refreshFailed();
			} else {// 更多
				parentLayout.loadmoreFailed();
			}
			refreshData();
			break;
		case ORDER_SAVEOPERATE:
			XtomToastUtil.showShortToast(getActivity(), "操作失败,请稍后再试");
			break;
		default:
			break;
		}
	}
	
	private void refreshData() {
		if (null == adapter) {
			adapter = new FarmerCustomOrderAdapter(getActivity(), mDatas, this);
            recyclerView.setAdapter(adapter);
            recyclerView.addItemDecoration(new RecyclerTenDecoration(getActivity()));
		}else {
			adapter.notifyDataSetChanged();
		}
	}

	@Override
	public void fetchData() {
		getCustomizeList();
	}

	@Override
	public void onItemClickListener(int position) {
        Intent intent = new Intent(getActivity(), FarmerCustomOrderDetailActivity.class);
        intent.putExtra("order", mDatas.get(position));
        startActivity(intent);
	}

	@Override
	public void onPay(int position) {

	}

	@Override
	public void onRefusePay(int position) {

	}

	@Override
	public void onPayBehalf(int position) {

	}

	@Override
	public void onCancel(int position) {

	}

	@Override
	public void onReceive(int position) {

	}

	@Override
	public void onAgreeReturn(int position) {

	}

	@Override
	public void onRefuseReturn(int position) {

	}

	@Override
	public void onDeliveryGoods(final int position) {
		final DeliveryDialog deliveryDialog = new DeliveryDialog(getActivity()).builder();
		deliveryDialog.setClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				String expressName = deliveryDialog.getExpressName();
				String expressNum = deliveryDialog.getExpressNum();
				if (isNull(expressName)) {
					XtomToastUtil.showShortToast(getActivity(), "快递公司名称不能为空!");
					return;
				}
				if (expressNum.isEmpty()) {
					XtomToastUtil.showShortToast(getActivity(), "快递单号不能为空!");
					return;
				}
				if (user != null && mDatas.get(position) != null) {
					getNetWorker().orderSaveoperate(user.getToken(), mDatas.get(position).getId(), "4", "无",
							"无", expressName, expressNum);
				}
				deliveryDialog.dismiss();
			}
		});
		deliveryDialog.show();
	}

    @Subscribe
    public void onEventMainThread(EventBusMsg msg) {
        if (msg.getType() == EventBusConfig.UPDATE_ORDER) {
            if (!isHidden()) {
                page = 0;
                getCustomizeList();
            }
        }
    }
}
